package com.data.controller;

import com.data.config.DynamicDataSourceContextHolder;
import com.data.entity.User;
import com.data.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 测试动态切换数据源插入，这边是在代码中写死具体哪个数据源，在实际项目中可以通过下面两种方式实现:
 * 1、通过dataSource注解来指定对应数据源
 * 2、通过拦截器在用户请求接口前获取当前用户租户信息，依据租户信息动态切换数据源
 * @author ytj
 * @date 2024/4/22
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/masterAdd")
    public void masterAdd(@RequestBody User user){
        this.userService.add(user);
    }

    @PostMapping("/slaveAdd")
    public void slaveAdd(@RequestBody User user){
        DynamicDataSourceContextHolder.removeDataSource();
        DynamicDataSourceContextHolder.setDataSource("slave");
        this.userService.add(user);
    }

    @PostMapping("/testAdd")
    public void testAdd(@RequestBody User user){
        DynamicDataSourceContextHolder.removeDataSource();
        DynamicDataSourceContextHolder.setDataSource("test");
        this.userService.add(user);
    }
}
